<?php
/**
 * HTTP事件响应
 * 
 * @author ShuangYa
 * @package APIGateway
 * @category Controller
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2018 ShuangYa
 * @license https://www.sylibs.com/go/apigateway/license
 */
namespace ag\controller\api;

use yesf\Yesf;
use yesf\library\ControllerAbstract;

use ag\library\Common;
use ag\library\Url;
use ag\library\Dispatcher;
use APIGateway\Protobuf\Request;

class Service extends ControllerAbstract {
	/**
	 * 调用单个接口
	 * 使用POST传输数据
	 * 如果header[x-request-type]为JSON，则请求和返回均使用JSON
	 * 否则均使用Protobuf
	 * 两种返回/请求方式格式一致
	 */
	public static function singleAction($request, $response) {
		//可以选择JSON或者Protobuf方式，默认为Protobuf
		$is_json = $request->headers['x-request-type'] === 'json';
		try {
			if ($is_json) {
				$data = Dispatcher::parseJson($request->rawContent());
			} else {
				$data = Dispatcher::parse($request->rawContent());
			}
		} catch (\Exception $e) {
			$result = Dispatcher::createResult(Dispatcher::CODE_WRONG_REQUEST, "");
		}
		if (!isset($result)) {
			$result = Dispatcher::dispatch($data);
		}
		if ($is_json) {
			$response->header('Content-Type', 'application/json; charset=UTF-8');
			$response->write($result->serializeToJsonString());
		} else {
			$response->header('Content-Type', 'application/octet-stream');
			$response->write($result->serializeToString());
		}
	}
}
